package com.bawei.lib_common.view

import android.app.Activity
import android.app.AlertDialog
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Environment
import android.provider.MediaStore
import android.util.AttributeSet
import android.util.Log
import android.view.ViewGroup
import android.widget.ImageView
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import com.bawei.lib_common.R
import com.bawei.lib_common.utils.ToastUtils
import com.bumptech.glide.Glide
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import kotlin.math.max

class FlowLayoutWithAddView@JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : ViewGroup(context, attrs, defStyleAttr) {
    private val addButton = ImageView(context).apply {
        setImageResource(R.drawable.ic_add_gray) // 深灰色加号图标
        background = ContextCompat.getDrawable(context, R.drawable.bg_add_button)
        setPadding(dpToPx(33f), dpToPx(33f), dpToPx(33f), dpToPx(33f))
        scaleType = ImageView.ScaleType.CENTER_INSIDE
        setOnClickListener { showImagePickerDialog() }
    }
    val list=mutableListOf<String>()

    private val itemSpacing = dpToPx(8f)
    private val lineSpacing = dpToPx(12f)
    private val imageViews = mutableListOf<ImageView>()

    init {
        addView(addButton)
        list.clear()
    }


    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val width = MeasureSpec.getSize(widthMeasureSpec)
        var height = MeasureSpec.getSize(heightMeasureSpec)
        var lineWidth = 0
        var lineHeight = 0

        // 测量所有子View
        for (i in 0 until childCount) {
            val child = getChildAt(i)
            measureChild(child, widthMeasureSpec, heightMeasureSpec)

            if (lineWidth + child.measuredWidth > width) {
                height += lineHeight + lineSpacing
                lineWidth = child.measuredWidth
                lineHeight = child.measuredHeight
            } else {
                lineWidth += child.measuredWidth + itemSpacing
                lineHeight = max(lineHeight, child.measuredHeight)
            }
        }
        height += lineHeight

        setMeasuredDimension(width, height)
    }

    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        var x = 0
        var y = 0
        var lineHeight = 0

        for (i in 0 until childCount) {
            val child = getChildAt(i)

            if (x + child.measuredWidth > width) {
                y += lineHeight + lineSpacing
                x = 0
                lineHeight = 0
            }

            child.layout(x, y, x + child.measuredWidth, y + child.measuredHeight)
            x += child.measuredWidth + itemSpacing
            lineHeight = max(lineHeight, child.measuredHeight)
        }
    }

    private fun showImagePickerDialog() {
        (context as? Activity)?.let { activity ->
            AlertDialog.Builder(activity)
                .setItems(arrayOf("拍照", "从相册选择")) { _, which ->
                    when (which) {
                        0 -> {
                            val hasCamera = context.packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)
                            if (!hasCamera) {
                                ToastUtils.showLong(context, "当前设备无摄像头")
                                return@setItems
                            }
                            openCamera(activity)
                        }
                        1 -> openGallery(activity)
                    }
                }
                .show()
        }
    }

    private fun openCamera(activity: Activity) {

        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE).apply {
            // 创建临时文件
            val photoFile = createImageFile(activity) // 需返回File对象
            val photoUri = FileProvider.getUriForFile(
                context,
                "com.bawei.numberone.fileprovider", // 必须与Manifest一致
                photoFile
            )
            putExtra(MediaStore.EXTRA_OUTPUT, photoUri)
            addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        }
        // 添加 try-catch 并启动相机
        try {
            activity.startActivityForResult(intent, REQUEST_CAMERA)
        } catch (e: ActivityNotFoundException) {
            ToastUtils.showLong(context, "未找到相机应用")
        } catch (e: SecurityException) {
            ToastUtils.showLong(context, "无相机权限")
        }
    }

    private fun openGallery(activity: Activity) {
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        activity.startActivityForResult(intent, REQUEST_GALLERY)
    }

    fun addImage(uri: Uri) {
        if (imageViews.size >= MAX_IMAGES) {
            ToastUtils.showLong(context, "最多添加$MAX_IMAGES 张图片")
            return
        }
        val imageView = ImageView(context).apply {
            layoutParams = LayoutParams(dpToPx(100f), dpToPx(100f))
            scaleType = ImageView.ScaleType.CENTER_CROP
            Glide.with(this).load(uri).into(this)
        }
        addView(imageView, childCount - 1) // 加号始终在最后
        imageViews.add(imageView)
        list.add(uri.toString())
        imageView.setOnLongClickListener {
            removeView(imageView)
            imageViews.remove(imageView)
            list.remove(uri.toString())
            true
        }
    }

    private fun dpToPx(dp: Float): Int = (dp * resources.displayMetrics.density).toInt()

    private fun createImageFile(context: Context): File {
        // 生成唯一文件名（时间戳格式）
        val timestamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
        val fileName = "JPEG_${timestamp}_"

        // 获取应用专属的图片存储目录
        val storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)

        // 创建临时文件
        return File.createTempFile(
            fileName,  /* 文件名前缀 */
            ".jpg",   /* 文件后缀 */
            storageDir /* 存储目录 */
        ).apply {
            // 可选：记录文件路径用于后续使用
            Log.d("Camera", "照片保存路径: ${absolutePath}")
        }
    }
    companion object {
        const val REQUEST_CAMERA = 100
        const val REQUEST_GALLERY = 101
        const val MAX_IMAGES = 9
    }
}